package coop.bancocredicoop.proyectos.gd

class DocumentsCSVWriter {
    
    def outputStream

    def DocumentsCSVWriter(outputStream) {
        this.outputStream = outputStream
    }

    void write(documents) {
        if (documents.size() == 0) {
            return
        }
        def title = ['idPersona', 'Denominacion', 'CUIT', 'Tipo de documento',
                     'Caja AdeA', 'Fecha de carga', 'Version']
        outputStream.write(getRow(title).getBytes("UTF-8"))
        documents.each { document -> 
            outputStream.write("\n".getBytes("UTF-8"))
            outputStream.write(getDocumentRow(document).getBytes("UTF-8"))
        }
    }

    def private getRow(fields) {
        def row = fields.collect { '"' + it.replace('"','""') + '"' }
        row.join(",")
    }

    def private getDocumentRow(document) {
        getRow([document.customer.idPersona.toString(), 
                document.customer.name,
                document.customer.cuit,
                document.documentType.name,
                document.box.cajaId,
                document.createdDate.format("yyyy-MM-dd HH:mm:ss"),
                document.realVersion.toString()])
    }

}

